package yto.freemarker.springaop.anno;


import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import yto.freemarker.springaop.dao.IndexMapper;
import yto.freemarker.springaop.factory.MyFactoryBean;

/**
 * 获取Bean注册器
 *
 * @author dongxing
 **/
public class MyBeanDefinitionRegistar implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
//
//        //想要注册的bean
//        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(MyFactoryBean.class);
//        //拿出BeanDefinition
//        AbstractBeanDefinition beanDefinition = beanDefinitionBuilder.getBeanDefinition();
//        //需要注册的Bean，支持Bean和路径扫描(传递参数进入factoryBean中，通过构造器的方式)
////        beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(IndexMapper.class);
//        beanDefinition.getConstructorArgumentValues().addGenericArgumentValue("yto.freemarker.springaop.dao.IndexMapper");
//        //注册Bean
//        registry.registerBeanDefinition("myfactoryBean",beanDefinition);

        Class[] clazzs = new Class[]{IndexMapper.class};
        for (Class aClass : clazzs) {
            //取出每个BeanDefinition
            BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(aClass);
            AbstractBeanDefinition beanDefinition = beanDefinitionBuilder.getBeanDefinition();
            //取出beanName
            String beanClassName = beanDefinition.getBeanClassName();
            //替换为factoryBean的值
            beanDefinition.setBeanClass(MyFactoryBean.class);
            beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(aClass.getName());
            registry.registerBeanDefinition(beanClassName,beanDefinition);
        }

    }
}
